package com.sysware.ccproxy;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * http 代理程序
 * 
 * @author lulaijun
 *
 */
public class SocketProxy {

	private static ServerSocket serverSocket;

	public static void initServerSocket(int port) throws IOException {
		serverSocket = new ServerSocket(port);
	}

	public static void close() throws IOException {
		serverSocket.close();
	}

	public static void main(String[] args) throws Exception {
		int listenPort = 80;
		if (args != null && args.length > 0 && args[0] != null) {
			listenPort = Integer.parseInt(args[0]);
		}

		initServerSocket(listenPort);

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		final ExecutorService executorService = Executors.newCachedThreadPool();
		System.out.println("Proxy Server Start At " + sdf.format(new Date()));
		System.out.println("listening port:" + listenPort + "……");
		System.out.println();

		while (true) {
			Socket socket = null;
			try {
				socket = serverSocket.accept();
				socket.setKeepAlive(true);
				// 加入任务列表，等待处理
				executorService.execute(new ProxyTask(socket));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

}
